package com.mengpeng.toastxutils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.*;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Method;

public class MToast {
    @SuppressLint("StaticFieldLeak")
    private static MToast mToast;
    private Context mContext;
    private MToastClickListener listener;
    private String content;
    private @ColorInt
    int contentTextColor = 0;
    private String btnText;
    private @ColorInt
    int btnTextColor = 0;
    private long duration;
    private Gravity gravity;
    private PopupWindow window;
    private int percent = 70;

    public static MToast getInstance(Context context) {
        if (mToast == null) {
            mToast = new MToast(context);
        }
        return mToast;
    }

    private MToast(Context context) {
        this.mContext = context;
    }

    public interface MToastClickListener {
        void onClickListener();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                if (window != null && window.isShowing()) {
                    window.dismiss();
                }
            }
        }
    };

    public MToast setPercent(int percent) {
        this.percent = percent;
        return mToast;
    }

    public MToast setDuration(long duration) {
        this.duration = duration;
        return mToast;
    }

    public MToast setContent(String content) {
        this.content = content;
        return mToast;
    }

    public MToast setBtnText(String btnText) {
        this.btnText = btnText;
        return mToast;
    }

    public MToast setContent(String content, @NotNull @ColorInt int contentTextColor) {
        this.content = content;
        this.contentTextColor = contentTextColor;
        return mToast;
    }

    public MToast setBtnText(String btnText, @NotNull @ColorInt int btnTextColor) {
        this.btnText = btnText;
        this.btnTextColor = btnTextColor;
        return mToast;
    }

    public MToast setGravity(Gravity gravity) {
        this.gravity = gravity;
        return mToast;
    }

    public MToast setListener(MToastClickListener listener) {
        this.listener = listener;
        return mToast;
    }

    @SuppressLint("InflateParams")
    public void show() {
        //设定默认显示方向
        if (gravity == null) {
            gravity = Gravity.LEFT;
        }
        View view;
        if (gravity == Gravity.LEFT) {
            view = LayoutInflater.from(mContext).inflate(R.layout.layout_toastx_left, null);
        } else {
            view = LayoutInflater.from(mContext).inflate(R.layout.layout_toastx_right, null);
        }

        RelativeLayout toastx_container = view.findViewById(R.id.toastx_container);
        TextView toastx_content = view.findViewById(R.id.toastx_content);
        TextView toastx_btn = view.findViewById(R.id.toastx_btn);
        //信息内容
        if (!TextUtils.isEmpty(content)) {
            toastx_content.setText(content);
            //信息字体颜色
            if (contentTextColor != 0) {
                toastx_content.setTextColor(contentTextColor);
            }
        }

        boolean focuable;
        //按钮字
        if (!TextUtils.isEmpty(btnText)) {
            toastx_btn.setText(btnText);
            toastx_btn.setVisibility(View.VISIBLE);
            focuable = listener != null;
            //按钮字体颜色
            if (btnTextColor != 0) {
                toastx_btn.setTextColor(btnTextColor);
            }
        } else {
            focuable = false;
            toastx_btn.setVisibility(View.GONE);
        }


        if (window != null && window.isShowing()) {
            window.dismiss();
            window = null;
        }
        window = new PopupWindow(view,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                focuable);
        // 设置PopupWindow是否能响应外部点击事件
        window.setOutsideTouchable(false);
        // 设置PopupWindow是否能响应点击事件
        window.setTouchable(true);

        //此时获取的是真实的屏幕高度
        DisplayMetrics metrics = new DisplayMetrics();
        Activity activity = (Activity) mContext;
        activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int heightPixels = metrics.heightPixels;

        int statusBarHeight = getStatusBarHeight(activity);
        int navigationBarHeight = 0;
        if (hasNavBar(activity)) {
            navigationBarHeight = getNavigationBarHeight(activity);
        }
        int height = heightPixels - statusBarHeight - navigationBarHeight;

        if (percent >= 100) {
            percent = 100;
        } else if (percent <= 0) {
            percent = 0;
        }

        if (gravity == MToast.Gravity.LEFT) {
            window.setAnimationStyle(R.style.toastx_left_anim_style);
        } else {
            window.setAnimationStyle(R.style.toastx_right_anim_style);
        }
        window.showAtLocation(window.getContentView(), android.view.Gravity.NO_GRAVITY, 0, height * percent / 100);

        //点击事件
        if (listener != null) {
            toastx_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (window != null) {
                        listener.onClickListener();
                        if (window.isShowing()) {
                            window.dismiss();
                            handler.removeMessages(1);
                        }
                    }
                }
            });
        }

        if (duration < 1000) {
            duration = 1000;
        }
        handler.sendEmptyMessageDelayed(1, duration);

        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (handler != null) {
                    handler.removeCallbacksAndMessages(null);
                }
            }
        });
    }

    public enum Gravity {
        LEFT, RIGHT
    }

    /**
     * 获取状态栏的高度
     */
    private static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    //获取虚拟按键的高度
    private static int getNavigationBarHeight(Context context) {
        int result = 0;
        if (hasNavBar(context)) {
            Resources res = context.getResources();
            int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = res.getDimensionPixelSize(resourceId);
            }
        }
        return result;
    }

    /**
     * 检查是否存在虚拟按键栏
     */
    private static boolean hasNavBar(Context context) {
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        if (resourceId != 0) {
            boolean hasNav = res.getBoolean(resourceId);
            // check override flag
            String sNavBarOverride = getNavBarOverride();
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
            return hasNav;
        } else { // fallback
            return !ViewConfiguration.get(context).hasPermanentMenuKey();
        }
    }

    /**
     * 判断虚拟按键栏是否重写
     */
    private static String getNavBarOverride() {
        String sNavBarOverride = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                @SuppressLint("PrivateApi") Class c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Throwable e) {
                e.fillInStackTrace();
            }
        }
        return sNavBarOverride;
    }

}
